package com.lamda.zhekou.controller;

import com.lamda.zhekou.utils.SMSUtil;
import com.lamda.zhekou.vo.ResultVo;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * Created by MJiao on 15/8/14.
 */
@Controller
public class VolidateCodeController {

    /**
     * @param phoneNum
     * @return
     */
    @RequestMapping(value = "/sendVerificatedCode")
    @ResponseBody
    public ResultVo sendVerificatedCode(HttpServletRequest httpServletRequest, @RequestParam(value = "phoneNum", required = true) long phoneNum) {
        ResultVo resultVo = new ResultVo();

        int max = 9999;
        int min = 1001;
        Random random = new Random();

        int volidateCode = random.nextInt(max) % (max - min + 1) + min;
        boolean succ = false;
        try {
            succ = SMSUtil.sendSMS(phoneNum, volidateCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resultVo.setSucc(succ);

        String msg = succ ? "验证码发送成功" : "验证码发送失败 ";
        resultVo.setMsg(msg);
        //将验证码保存到session
        httpServletRequest.getSession(true).setAttribute("volidateCode", volidateCode);
        System.out.println("volidateCode = " + volidateCode);
        return resultVo;
    }
}
